

var intercom = {
	handler: [],
	register: function(cmd, callback, context){
		this.handler.push( {"cmd":cmd,"callback":callback,"context":context});
	},
	catcher : function( e){
		var ret = {},
			fn = this.handler.filter( function( handle){
				return handle.cmd === e.data.cmd;
			},this);
		
		if( fn.length ===0){
			return "fail.";
		}
		if( fn.length >1){
			return "too many handlers";
		}
		fn=fn[0];
		try{
			ret = fn.callback.call(fn.context,e.data);
		}catch(error){
			cl(e.data.cmd);
			
			throw(error);
		}
		if(ret===undefined){
			ret = {cmd:"void"};
		}
		if(!ret.refid){
			ret.refid = e.data.refid;
		}
		postMessage( ret);
	}
};

function cl( a){
	postMessage({cmd:"cl",args:{value:a}});
}

function tempCatcher(e){
	intercom.catcher(e);
}
globalObj.onmessage = tempCatcher;

intercom.register("init", function(e){
	sdkHistory.base( sdkSlice(e.args.field));
	return getHandler({args:{value:"field"}});
});

function getHandler(e){
	switch( e.args.value){
		case "field":
			return {
				cmd: "post_field",
				args: {
					value: sdkHistory.current()
				}
			};
		case "cell":
			return {
				cmd: "post_cell",
				args: {
					value: sdkHistory.current().filterByID(e.args.cellID)
				}
			};
		case "all_candids":
			return {
				cmd: "post_all_candids",
				args:{
					value: rules.candidIDs
				}
			};
		case "filter":
            return { };
		default:
			if(rules[e.args.value]){
				return {
					cmd: "post_"+e.args.value,
					args:{
						value: rules[e.args.value]
					}
				};
			}
			return undefined;
	}
}
intercom.register("get", getHandler);

intercom.register("get_multiple",function(e){
	var ret = {};
	for( var i=0; i<e.args.values.length;i++){
		var req= e.args.values[i];
		ret[req]=getHandler({args:{value:req}}).args.value;
	}
	return {cmd:"post_multiple",args:ret};
});
intercom.register("status",function(e){
	return {
		cmd:"cl",
		args:{
			value:sdkHistory
		}
	};
});
intercom.register("change",function(e){
switch( e.args.value){
	case "swap":
		//history.unshift( sdkChange("swap",e.args.cellID,e.args.candidID));
		//field = history[0].exec( field);
		sdkHistory.next( sdkChange("swap",e.args.cellID,e.args.candidID));
		return getHandler({args:{value:"cell",cellID:e.args.cellID}});
	case "only":
		//history.unshift( sdkChange("only",[e.args.cellID],[e.args.candidID]));
		//field = history[0].exec( field);
		sdkHistory.next( sdkChange("only",e.args.cellID,e.args.candidID));
		return getHandler({args:{value:"cell",cellID:e.args.cellID}});
}});
intercom.register("calc",function(e){
	if( algors[e.args.value]){
		sdkHistory.next( algors[e.args.value]( sdkHistory.current()));
		return getHandler({args:{value:"field"}});
	}
});
